var express = require('express');
var router = express.Router();
const { Course, Category, Chapter, User } = require('../models');
const { Op } = require('sequelize');
const { success, failure } = require('../utils/responses');

/* 
*  搜索课程列表
*/
router.get('/', async function (req, res, next) {
    try {
        console.log('res111111111111111111111=>',req)
        const query = req.query;
        // 页和每页现实几条数据
        const currentPage = Math.abs(Number(query.currentPage)) || 1;
        const pageSize = Math.abs(Number(query.pageSize)) || 10;
        const offset = (currentPage - 1) * pageSize;

        const condition = {
            attributes: { exclude: ['CategoryId', 'UserId', 'content'] },
            order: [['id', 'DESC']],
            offset: offset,
            limit: pageSize,
            where:{}
        }
        if (query.name) {
            condition.where.name = {
                [Op.like]: `%${query.name}%`
            }
        }
        const { count, rows } = await Course.findAndCountAll(condition);
        success(
            res,
            '搜索课程列表成功',
            {
                course: rows,
                pagination: {
                    total: count,
                    currentPage,
                    pageSize
                }
            }
        )
    } catch (error) {
        failure(res, error)
    }
});


// // 查询课程详情
// router.get('/:id', async function (req, res, next) {
//     try {
//         const { id } = req.params;
//         const condition = {
//             attributes: { exclude: ['CategoryId', 'UserId'] },
//             include: [
//                 { model: Category, as: 'category', attributes: ['id', 'name'] },
//                 {
//                     model: Chapter, as: 'chapters',
//                     attributes: ['id', 'title', 'rank','createdAt'],
//                     order: [['rank', 'ASC'], ['id', 'DESC']]
//                 },
//                 {
//                     model: User, as: 'user',
//                     attributes: ['id', 'username', 'nickname', 'avatar', 'company']
//                 },
//             ]
//         };

//         const course = await Course.findByPk(id, condition);
//         if (!course) {
//             throw new NotFoundError(`ID: ${id}的课程未找到`)
//         }
//         success(
//             res,
//             '查询课程成功',
//             {course}
//         )

//     } catch (error) {
//         failure(res, error)
//     }
// });


module.exports = router;
